package com.handong.handserialprogram.module.tasklist;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.broadcastreceiver.BatteryBroadcastReceiver;
import com.handong.handserialprogram.broadcastreceiver.F1KeyCastReceiver;
import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.entities.MissionEntity;
import com.handong.handserialprogram.module.base.BaseActivity;
import com.handong.handserialprogram.module.choosering.ChooseRingActivity;
import com.handong.handserialprogram.module.createmission.CreateMissionActivity;
import com.handong.handserialprogram.module.others.OtherActivity;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.module.setting.AppFragment;
import com.handong.handserialprogram.module.setting.SettingActivity;
import com.handong.handserialprogram.module.setting.SupportFragment;
import com.handong.handserialprogram.module.singletask.MissionActivity;
import com.handong.handserialprogram.ui.QRCodeActivity;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.LockUtil;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.SystemUtil;
import com.handong.handserialprogram.utils.ViewUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.pda.serialport.Tools;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import io.reactivex.disposables.Disposable;



public class TaskListActivity extends BaseActivity<TaskListPresenter> implements TaskListContract.View {

    private static final String TAG = TaskListActivity.class.getSimpleName();

    private PtrClassicFrameLayout mFrameLayout;
    private RecyclerView mTaskListRecyclerView;
    private TaskListAdapter mTaskListAdapter;
    private DrawerLayout mTaskListDrawerLayout;
    private RelativeLayout mNavLayout;
    private SerialPortUtil mSerialPortUtil;

    //private MaterialDialog mProgressDialog;

    private TextView mUserName, mExitText,mAesUtils;

    private LinearLayoutManager mLayoutManager;
    private ImageView mExitIcon;
    private LinearLayout mRequestMissionTip;

    private SearchView mMissionSearch;

    private long mExitTime;

    private EditText mEditText;
    private BatteryBroadcastReceiver mBatteryChanged;
    private F1KeyCastReceiver mF1KeyListener;
    private int GPS_REQUEST_CODE = 10;

    //private TextView mProgressText;


    private Disposable mDisposable;//可以取消观察者
    //



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentViewID() {
        return R.layout.activity_list_drawerlayout;
    }

    @Override
    protected TaskListPresenter createPresenter() {
        return new TaskListPresenter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mTaskListAdapter != null && !TextUtils.isEmpty(SPUtil.getStringValue(SPUtil.LOGIN_CODE))) {
            mPresenter.loadTaskList();
        }
        mSerialPortUtil = SerialPortUtil.getInstance(this);
        if (mSerialPortUtil != null) {
            mSerialPortUtil.closeSerialPort();
        }
    }

    @Override
    protected void initViewByID() {
        mFrameLayout = (PtrClassicFrameLayout) findViewById(R.id.taskListPtrLayout);
        mTaskListRecyclerView = (RecyclerView) findViewById(R.id.taskListRecyclerView);

        mTaskListDrawerLayout = (DrawerLayout) findViewById(R.id.taskListDrawerlayout);
        mNavLayout = (RelativeLayout) findViewById(R.id.navTaskList);
        mUserName = (TextView) findViewById(R.id.navUserName);
        mAesUtils = (TextView) findViewById(R.id.aesUtils);
        findViewById(R.id.navAboutUs).setOnClickListener(this);
        findViewById(R.id.technologySupport).setOnClickListener(this);
        findViewById(R.id.systemVersion).setOnClickListener(this);
        findViewById(R.id.navIPAddressSetting).setOnClickListener(this);
        findViewById(R.id.navFootRingSetting).setOnClickListener(this);
        findViewById(R.id.navFootRingOut).setOnClickListener(this);


        mRequestMissionTip = (LinearLayout) findViewById(R.id.missionTipLayout);

        findViewById(R.id.navBottomSetting).setOnClickListener(this);
        findViewById(R.id.navBottomLogout).setOnClickListener(this);
        findViewById(R.id.btnCreateMission).setOnClickListener(this);

        mExitText = (TextView) findViewById(R.id.navExitText);
        mExitIcon = (ImageView) findViewById(R.id.navExitIcon);

        mNavLayout.setOnClickListener(this);
        mRequestMissionTip.setOnClickListener(this);
    }

    @Override
    protected void initViewDataRes() {
        initHeaderLayout(true);
        setCenterTitle(R.string.title_mission_list);
        //todo

        LockUtil.lockHomeClick(this);
        LockUtil.lockMenuClick(this);
        LockUtil.lockStatusBar(this);

        mFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //下拉刷新
                mPresenter.loadTaskList();
            }
        });
        //判断用户登录状态。
        try {
            if (!TextUtils.isEmpty(SPUtil.getStringValue(SPUtil.LOGIN_CODE))) {
                mUserName.setText("( 用户: " + SPUtil.getStringValue(SPUtil.USER_NAME) + " )");
                mExitText.setText(R.string.nav_login_success);
                mExitIcon.setImageResource(R.drawable.icon_nav_exit);

                showLoadDialog("任务列表加载中...");
                mFrameLayout.autoRefresh();
            } else {
                mUserName.setText(getApplicationContext().getResources().getText(R.string.nav_user_name));

                mExitText.setText(R.string.nav_login_empty);
                mExitIcon.setImageResource(R.drawable.icon_nav_login1);

                mPresenter.showLoginDialog();
            }

        } catch (Exception ex) {
            mUserName.setText(getApplicationContext().getResources().getText(R.string.nav_user_name));

            mExitText.setText(R.string.nav_login_empty);
            mExitIcon.setImageResource(R.drawable.icon_nav_login1);

            mPresenter.showLoginDialog();
            Log.d(TAG, "initViewDataRes: ", ex);
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        mBatteryChanged = new BatteryBroadcastReceiver();
        this.registerReceiver(mBatteryChanged, filter);
        IntentFilter f1Filter = new IntentFilter();
        f1Filter.addAction("android.rfid.FUN_KEY");
        f1Filter.addAction("android.intent.action.FUN_KEY");
        mF1KeyListener = new F1KeyCastReceiver();
        registerReceiver(mF1KeyListener, f1Filter);

        final Context context = this;
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager != null && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            AppUtil.openWifi(context);
        }
//        if(SPUtil.getBooleanValue(SPUtil.isLoginOut)){
//            mAesUtils.setText("注销脚环");
//        }
        openGPSSettings();
    }


    /**
     * 检测GPS是否打开
     *
     * @return
     */
    private boolean checkGPSIsOpen() {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
        return isOpen;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    /**
     * 跳转GPS设置
     */
    private void openGPSSettings() {
        if (!checkGPSIsOpen()) {
            //没有打开则弹出对话框
            ViewUtil.removeAllKeyListener(new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_info)
                    .content("当前应用需要打开位置信息功能,请开启位置信息功能。")
                    .positiveText(R.string.dialog_positive_text)
                    .canceledOnTouchOutside(false)
                    .positiveColorRes(R.color.back_ground_green)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                            //跳转GPS设置界面
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, GPS_REQUEST_CODE);
                        }
                    }).build());

        }
    }


    protected void loginUserSuccess(String name) {
        mUserName.setText("( 用户: " + SPUtil.getStringValue(SPUtil.USER_NAME) + " )");
        mExitText.setText(R.string.nav_login_success);
        mExitIcon.setImageResource(R.drawable.icon_nav_exit);

        mTaskListDrawerLayout.closeDrawer(GravityCompat.START);

        showLoadDialog("任务列表加载中...");
        mFrameLayout.autoRefresh();
    }

    /**
     * 显示任务列表
     */
    @Override
    public void showTaskList(List<MissionEntity> missionList) {
        dismissLoadingDialog();

        if (mTaskListAdapter == null) {
            mTaskListAdapter = new TaskListAdapter(this, missionList);
            mTaskListRecyclerView.setAdapter(mTaskListAdapter);
            mLayoutManager = new LinearLayoutManager(getApplicationContext());
            mTaskListRecyclerView.setLayoutManager(mLayoutManager);
        } else {
            mTaskListAdapter.setTaskList(missionList);
        }
        mFrameLayout.setVisibility(View.VISIBLE);
        mRequestMissionTip.setVisibility(View.GONE);
        mFrameLayout.refreshComplete();
    }

    /**
     * 未获取到数据
     */
    public void noExecutingMission() {
        dismissLoadingDialog();
        if (mTaskListAdapter == null) {
            mTaskListAdapter = new TaskListAdapter(this, null);
            mTaskListRecyclerView.setAdapter(mTaskListAdapter);
            mLayoutManager = new LinearLayoutManager(getApplicationContext());
            mTaskListRecyclerView.setLayoutManager(mLayoutManager);
        } else {
            mTaskListAdapter.setTaskList(null);
        }
        mFrameLayout.setVisibility(View.GONE);
        mRequestMissionTip.setVisibility(View.VISIBLE);

        refreshTipLayout(R.drawable.load_tip_no_mission, R.string.tip_no_mission_list);
        mFrameLayout.refreshComplete();
    }

    /**
     * 加载失败
     */
    @Override
    public void showLoadingFail() {
        dismissLoadingDialog();
        if (mFrameLayout.getVisibility() == View.VISIBLE) {
            mFrameLayout.setVisibility(View.GONE);
        }
        if (mRequestMissionTip.getVisibility() == View.GONE) {
            mRequestMissionTip.setVisibility(View.VISIBLE);
        }
        refreshTipLayout(R.drawable.load_tip_error, R.string.tip_load_miss_error);
        mFrameLayout.refreshComplete();
    }

    private void refreshTipLayout(int imageId, int textId) {
        ImageView imageView = (ImageView) mRequestMissionTip.getChildAt(0);
        imageView.setImageResource(imageId);
        TextView textView = (TextView) mRequestMissionTip.getChildAt(1);
        textView.setText(textId);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return false;
    }

    @Override
    public void moveToSearchResult(int position) {
        ViewUtil.moveToPosition(mLayoutManager, mTaskListRecyclerView, position);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.headerBackLayout://打开菜单
                if (mTaskListDrawerLayout != null) {
                    mTaskListDrawerLayout.openDrawer(GravityCompat.START);
                }
                break;
            case R.id.navAboutUs://使用帮助
                Bundle bundle0 = new Bundle();
                bundle0.putInt(SPUtil.NAV_INDEX, OtherActivity.INDEX_USER_HELPER);
                openActivity(OtherActivity.class, bundle0);
                break;

            case R.id.technologySupport:  //技术支持
                Bundle bundle2 = new Bundle();
                bundle2.putInt(SPUtil.NAV_INDEX, OtherActivity.INDEX_TECH_SUPP);
                openActivity(OtherActivity.class, bundle2);
                JLog.d("SettingFragment", "case R.id.technologySupport:");
                break;

            case R.id.systemVersion:   //设备信息
                Bundle bundle3 = new Bundle();
                bundle3.putInt(SPUtil.NAV_INDEX, OtherActivity.INDEX_DEVICE_INFO);
                openActivity(OtherActivity.class, bundle3);
                break;

            case R.id.missionTipLayout://点击刷新
                if (TextUtils.isEmpty(SPUtil.getStringValue(SPUtil.LOGIN_CODE))) {
                    mPresenter.showLoginDialog();
                    return;
                }
                if (AsyncHttpUtil.isNetworkConnected(this)) {
                    showLoadDialog("任务列表加载中...");
                    mPresenter.loadTaskList();
                } else {
                    openNetwork();
                }
                break;

            case R.id.navTaskList:
                break;

            case R.id.navIPAddressSetting://配置服务器端口
                Bundle bundle4 = new Bundle();
                bundle4.putInt(SPUtil.NAV_INDEX, 4);
                //openActivity(OtherActivity.class, bundle4);
                openActWithAnim(OtherActivity.class, bundle4, 4, OtherActivity.INDEX_CONFIG_SERVER);
                break;

            case R.id.navFootRingSetting://注销脚环
//                if(!SPUtil.getBooleanValue(SPUtil.isLoginOut)){
                    openQRActivity();
//                }else {
//
//                }

                break;
            case R.id.navFootRingOut:
                inputFootRingIdDialog();
                break;
            case R.id.navBottomSetting://设置
                openActivity(SettingActivity.class);
                break;

            case R.id.navBottomLogout://注销
                if (TextUtils.isEmpty(SPUtil.getStringValue(SPUtil.LOGIN_CODE))) {
                    mPresenter.showLoginDialog();
                    return;
                }
                showLogoutDialog();

                break;

            case R.id.btnCreateMission://创建任务
                if (!AsyncHttpUtil.isNetworkConnected(this)) {
                    openNetwork();
                    return;
                }
                if (TextUtils.isEmpty(SPUtil.getStringValue(SPUtil.LOGIN_CODE))) {
                    mPresenter.showLoginDialog();
                    return;
                }
                if (mPresenter.isMissionExecuting()) {//检查未完成的任务
                    return;
                }

                Bundle cBundle = new Bundle();
                openActivity(CreateMissionActivity.class, cBundle);//创建任务
                break;

            default:
                super.onClick(v);
                break;
        }
    }

    private void openQRActivity() {
        startActivityForResult(new Intent(this, QRCodeActivity.class), 300);
    }

    public boolean isMissionExecuting() {
        return mPresenter.isMissionExecuting();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OtherActivity.INDEX_CONFIG_SERVER && resultCode == OtherActivity.INDEX_CONFIG_SERVER) {
            resetLoginStatus();
        }
        if (requestCode == GPS_REQUEST_CODE) {
            //做需要做的事情，比如再次检测是否打开GPS了 或者定位
            openGPSSettings();
        }
        if (requestCode == 300) {
            if (data == null) {
                return;
            }else {
                try {
                    String code = data.getStringExtra("QRString");
                    Log.d("data:code==", code+"=="+"Imei:"+ Tools.getIMEI(this)+"  time"+releaseTime());
                    if (code==null){
                        AppUtil.showShortToast(context, "加密字段错误");
                        return;
                    }
                    String[] qrString = code.split("\\+");
                    Log.d("data:code==", "长度："+qrString.length+"=="+"  time:"+qrString[0]+"Imei:"+qrString[1]+"IP1:"+qrString[2]+"IP2:"+qrString[3]);


                    if (Integer.parseInt(qrString[0]) < Integer.parseInt(releaseTime())){
                        AppUtil.showShortToast(context, "序列号已过期，需要更新");
                        return;
                    }
                    if (!qrString[1].equals(Tools.getIMEI(this))){
                        AppUtil.showShortToast(context, "IMEI匹配失败");
                        return;
                    }
                    SPUtil.putStringValue(SPUtil.LoginOutTime,qrString[0]);
                    SPUtil.putStringValue(SPUtil.FOOTRING_SERVER_IP,qrString[3]);
                    SPUtil.putStringValue(SPUtil.SERVER_IP, qrString[2]);
                    SPUtil.putBooleanValue(SPUtil.isLoginOut,true);
//                    mAesUtils.setText("注销脚环");
                }catch (Exception e){
                    Log.d("错误信息", e.toString());
                    AppUtil.showShortToast(context, "二维码信息错误");
                }

            }



        }
    }

    //获取当前时间
    private  static String releaseTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String dateTime = format.format(new Date());
        return dateTime;

    }
    /**
     * 输入脚环ID
     */
    private void  inputFootRingIdDialog() {
        final Context context = this;
        mSerialPortUtil.openSerialPortToReadData();
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("脚环编码")
                .input("请输入脚环编码,多个用分号隔开", null, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                        //if(input.length()>4) dialog.getInputEditText().setText(input.subSequence(0,4)) ;
                    }
                })
                .canceledOnTouchOutside(false)
                .autoDismiss(false)
                .positiveText(R.string.dialog_positive_text)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (dialog.getInputEditText().getText() != null) {
                            String password = dialog.getInputEditText().getText().toString().toUpperCase();
                            SPUtil.putStringValue(SPUtil.FOOT_RING_STRING,password);
                            if (CheckRingId(password)) {
                                String[] RingIdArray = password.split(";");
                                for (String RingId :
                                        RingIdArray) {
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    mSerialPortUtil.sendLoginOutFootRing(RingId);
                                }
                                try {
                                    Thread.sleep(200);
                                    mSerialPortUtil.closeSerialPort();
                                    dialog.dismiss();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                AppUtil.showShortToast(context, "注销命令已发送！");
//                                 Bundle bundle = new Bundle();
//                                bundle.putString(KeyConstant.LOGIN_OUT_RING_ID, password);
//                                openActivity(LoginOutRingActivity.class, bundle);

                            } else {
                                AppUtil.showShortToast(context, "脚环编码格式错误！");
                            }
                        } else {
                            AppUtil.showShortToast(context, "脚环编码不能为空！");
                        }
                    }
                })
                .negativeColorRes(R.color.dialog_bg)
                .negativeText(R.string.dialog_negative_text)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .build();
//        Log.d("zzzz","string:"+SPUtil.getStringValue(SPUtil.FOOT_RING_STRING).toString());
        if (SPUtil.getStringValue(SPUtil.FOOT_RING_STRING)!=null){
            dialog.getInputEditText().setText(SPUtil.getStringValue(SPUtil.FOOT_RING_STRING));
        }
        ViewUtil.removeHomeKeyListener(dialog);
    }

    //验证是否为HEX字符
    public static boolean IsHexChar(String str) {
        String regex = "^[a-fA-F0-9]+$";
        return match(regex, str);
    }

    private static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    private boolean CheckRingId(String ringId) {
        if (ringId.contains(";")) {
            String[] RingIdArray = ringId.split(";");
            for (String RingId :
                    RingIdArray) {
                if (RingId.length() != 4 || !IsHexChar(RingId)) {
                    return false;
                }
            }
            return true;
        } else {
            if (ringId.length() != 4 || !IsHexChar(ringId)) {
                return false;
            } else {
                return true;
            }
        }
    }








    final Context context = this;
    //观察者

    /**
     * 注销账号
     */
    private void showLogoutDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_logout_user)
                .customView(getUserInfoView(), true)
                .positiveColorRes(R.color.back_ground_green)
                .negativeText(R.string.dialog_negative_text)
                .positiveText(R.string.dialog_positive_text)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        resetLoginStatus();
                        showShortToast("当前账号已退出");
                        mTaskListDrawerLayout.closeDrawer(GravityCompat.START);
                    }
                })
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 重置登录状态UI
     */
    private void resetLoginStatus() {
        mUserName.setText(R.string.nav_user_name);
        SPUtil.remove(SPUtil.LOGIN_CODE);
        //SPUtil.remove(SPUtil.USER_NAME);
        mExitText.setText(R.string.nav_login_empty);
        mExitIcon.setImageResource(R.drawable.icon_nav_login1);

        if (mTaskListAdapter == null) {
            mTaskListAdapter = new TaskListAdapter(this, null);
            mTaskListRecyclerView.setAdapter(mTaskListAdapter);
            mLayoutManager = new LinearLayoutManager(getApplicationContext());
            mTaskListRecyclerView.setLayoutManager(mLayoutManager);
        } else {
            mTaskListAdapter.setTaskList(null);
        }
        mFrameLayout.setVisibility(View.GONE);
        mRequestMissionTip.setVisibility(View.VISIBLE);
        refreshTipLayout(R.drawable.tip_login_to_server, R.string.tip_please_login_first);
    }

    private View getUserInfoView() {
        LinearLayout layout = new LinearLayout(this.getApplicationContext());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setLayoutParams(params);

        String name = SPUtil.getStringValue(SPUtil.USER_NAME);
        float dpi = SystemUtil.displayMetricsDpi(getApplicationContext());

        TextView user = new TextView(getApplicationContext());
        LinearLayout.LayoutParams param1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        //param1.gravity = Gravity.CENTER_VERTICAL;
        user.setPadding(0, Math.round(15 * dpi), 0, Math.round(15 * dpi));
        user.setText("当前已登录账号：" + name);
        user.setLayoutParams(param1);
        user.setTextSize(Math.round(12 * dpi));
        user.setTextColor(getApplicationContext().getResources().getColor(R.color.text_content));
        layout.addView(user);

        TextView tip = new TextView(getApplicationContext());
        LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        //param2.gravity = Gravity.CENTER_VERTICAL;
        tip.setTextColor(getApplicationContext().getResources().getColor(R.color.text_content));
        tip.setPadding(0, 0, 0, Math.round(15 * dpi));
        tip.setText("（退出后会清除账号的相关任务信息）");
        tip.setLayoutParams(param2);
        tip.setTextSize(Math.round(10 * dpi));
        layout.addView(tip);

        return layout;
    }

    @Override
    public void onBackPressed() {
        if (mMissionSearch != null && mMissionSearch.isShown()) {
            mMissionSearch.clearFocus();
            return;
        }
        if (mTaskListDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mTaskListDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            exitDialog();
        }
    }

    private void exitDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_exit_program)
                .content(R.string.dialog_content_input_psd)
                .inputType(2)
                .inputRange(2, 16)
                .positiveColorRes(R.color.back_ground_green)
                .positiveText(R.string.dialog_positive_text)
                .negativeColorRes(R.color.dialog_bg)
                .negativeText(R.string.dialog_negative_text)
                .autoDismiss(false)
                .input("仅限数字", "", false, new MaterialDialog.InputCallback() {
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence sequence) {
                        if (sequence.toString().equals(SPUtil.getStringValue(SPUtil.USER_PASSWORD, "123456"))) {
                            dialog.dismiss();
                            LockUtil.releaseLockHome(TaskListActivity.this);
                            LockUtil.releaseMenuLock(TaskListActivity.this);
                            LockUtil.releaseStatusBarLock(TaskListActivity.this);
                            TaskListActivity.this.finish();
                            android.os.Process.killProcess(android.os.Process.myPid());
                            System.exit(0);
                            return;
                        }
                        AppUtil.showShortToast(TaskListActivity.this.getApplicationContext(), "密码错误");
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .checkBoxPromptRes(R.string.show_password, false, new CompoundButton.OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                        if (isChecked) {
                            mEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        } else {
                            mEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        }
                        int index = mEditText.getText().length();
                        if (index != 0) {
                            mEditText.setSelection(index);
                        }
                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        mEditText.setCursorVisible(false);
                        mEditText = null;
                    }
                })
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
        this.mEditText = dialog.getInputEditText();
        mEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }

    /**
     * 加入任务
     */
    protected void showJoinTipDialog(final Bundle bundle) {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_careful)
                .content("本机设备编号: " + SPUtil.getStringValue(SPUtil.PHONE_NAME) +
                        "\n\n不属于该任务，是否选择脚环，加入任务？")
                .negativeColorRes(R.color.bg_gray)
                .canceledOnTouchOutside(false)
                .negativeText(R.string.dialog_negative_text)
                .positiveText(R.string.dialog_positive_text)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        openActivity(ChooseRingActivity.class, bundle);
                    }
                }).build();
        dialog.show();
    }

    /**
     * 存在未完成的任务
     */
    protected void showExecutingMissDialog(final MissionEntity entity) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_mission_working, null);
        TextView name = (TextView) contentView.findViewById(R.id.ownDeviceName);
        name.setText("本机设备编号: " + SPUtil.getStringValue(SPUtil.PHONE_NAME));
        TextView missName = (TextView) contentView.findViewById(R.id.ownWorkingMiss);
        missName.setText("存在未完成的任务: " + entity.getTaskName());

        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_careful)
                .customView(contentView, true)
                .negativeColorRes(R.color.bg_gray)
                .canceledOnTouchOutside(false)
                .negativeText(R.string.dialog_negative_text)
                .positiveText(R.string.dialog_positive_now_execute)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        decideToDifferentAct(entity);
                    }
                }).build();
        dialog.show();
    }

    /**
     * 根据不通的任务选择不同的界面
     */
    protected void decideToDifferentAct(MissionEntity entity) {
        Bundle bundle = new Bundle();
        bundle.putString(KeyConstant.MISSION_ID, entity.getTaskId());
        bundle.putString(KeyConstant.MISSION_NAME, entity.getTaskName());
        bundle.putSerializable(KeyConstant.CRIMINALS_LIST, entity.getCriminal());
        if (entity.ispInTask()) {
            if (entity.isTaskHasCriminal()) {
                bundle.putString(KeyConstant.MISSION_CAR, entity.getTaskEscortCar());
                bundle.putString(KeyConstant.MISSION_TIME, entity.getTaskStartDate());
                openActivity(MissionActivity.class, bundle);
            } else {
                bundle.putBoolean(KeyConstant.IS_JOIN, false);
                openActivity(ChooseRingActivity.class, bundle);
            }
        } else {
            bundle.putBoolean(KeyConstant.IS_JOIN, true);
            showJoinTipDialog(bundle);
        }
    }

    @Override
    protected void onDestroy() {
        if (mBatteryChanged != null) {
            this.unregisterReceiver(mBatteryChanged);
            mBatteryChanged = null;
        }
        if (mF1KeyListener != null) {
            this.unregisterReceiver(mF1KeyListener);
            mF1KeyListener = null;
        }
        if (mLayoutManager != null) {
            mLayoutManager = null;
        }
        if (mDisposable != null) {
            //取消监听
            mDisposable.dispose();
        }
        super.onDestroy();
    }
}
